<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\api\model\Product as ProductMpdel;
use app\api\model\ProductGuige;
use app\admin\model\User;
use app\api\model\UserAddress;
use app\api\model\Order;
use app\common\model\ScoreLog;
use app\api\model\ProductDetails;
use app\api\model\GuigeValue;
use app\api\model\FaProductSpeci;
use app\api\model\FaProductSpeciList;
use think\Db;

/**
 * 商品接口
 */
class Product extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    /**
     * 商品列表
     */ 
    public function list()
    {
        $page = $this->request->get('page');
        $limit = $this->request->get('limit');
        $type = $this->request->get('type');
        $type = empty($type)?1:$type;
        $page = empty($page) ? 1 : $page;
        $limit = empty($limit) ? 10 : $limit;
        $userId = $this->auth->id;
        $list = ProductMpdel :: where(['type'=>$type])->page($page,$limit)->select();
        $count = count($list);
        foreach ($list as $key => $val) {
            if ($val['img']) {
                $list[$key]['img'] = 'https://' . $_SERVER['HTTP_HOST'] . $val['img'];
            }
        } 
        $data = [
            'list' => $list,
            'count' => $count,
            ];
        $this->success('获取成功',$data);
    }

    /**
     * 商品详情
     */
    public function details(){
        $data = $this->request->param();
        $goodsInfo = ProductMpdel::where('product_id',$data['id'])->find();
        $goodsInfo['img'] = 'https://' . $_SERVER['HTTP_HOST'] . $goodsInfo['img'];
        $attr = FaProductSpeci::where('product_id',$goodsInfo['product_id'])->select();
        foreach($attr as $k=>$v){
           $attr[$k]['sonSpeci'] = FaProductSpeciList::where('speci_id',$v['speci_id'])->select();
        }
        $postData = [
            'goodsInfo'=>$goodsInfo,
            'attr'=>$attr,
        ];

        $this->success('获取成功',$postData);
    }


    /**
     * 查看是否可以兑换 
     */
    public function lack()
    {
        $id = $this->request->get('id');
        $guige_id = $this->request->get('guige_id');
        $va_id = $this->request->get('va_id');
        $userId = $this->auth->id;
        $details = ProductDetails::where(['pr_id'=>$id,'ge_id'=>$guige_id,'va_id'=>$va_id])->find();
        if (!$details) {
            $this->error('没有当前规格');
        }
        $score = 0;
        if ($userId) {
            $score = User::where('id',$userId)->value('score');
        }
        if ($score <  $details['integral']) {
            $a = '还差'.bcsub( $details['integral'],$score).'积分';
        } else {
            $a = '';
        }
        $this->success('获取成功',[$a]);

    }

    /**
     * 立即兑换（创建订单）
     */ 
    public function creation_order(){
        $data = $this->request->post();
        $userId = $this->auth->id;
        if (!$userId) {
            $this->error('参数错误');
        }
        $goodsInfo = ProductMpdel::where('product_id',$data['product_id'])->find();
        $score = User::where('id',$userId)->value('score');
        if($data['price'] > $score){
            $this->error('积分不足！');
        }
        $addressInfo = UserAddress::where('uid',$userId)->where('top',1)->find();
        if(empty($addressInfo)){
            $this->error('无收货地址！');
        }
        if($goodsInfo['type'] == 1){
            $order_satae = 1;
        }else{
            $order_satae = 3;
        }
        Db::startTrans();
        try {
            $order_num = 'HQ'.time().mt_rand(1000,9999);
            $postData = [
                'uid'=>$userId,
                'product_id'=>$data['product_id'],
                'order_num'=> $order_num,
                'product'=>$goodsInfo['product'],
                'img'=>$goodsInfo['img'],
                'attr'=>$data['attr'],
                'integral'=>$data['price'],
                'name'=>$addressInfo['name'],
                'phone'=>$addressInfo['phone'],
                'province'=>$addressInfo['province'],
                'city'=>$addressInfo['city'],
                'area'=>$addressInfo['area'],
                'address'=>$addressInfo['address'],
                'order_satae'=>$order_satae,
                'jd_mobile'=>$data['jd_mobile'],
                'goods_type'=>$goodsInfo['type'],
                'goods_number'=>1,
            ];
            $Order = new Order;
            $Order->save($postData);
            $scoreLogData = [
                'user_id' => $userId,
                'before'=> $score,
                'score' => $data['price'],
                'after' => bcsub($score,$data['price']),
                'type' => 2,
                'memo' =>'兑换商品'
            ];
            ScoreLog::create($scoreLogData);
            $userinfo =  User::where('id',$userId)->find();
            $userinfo->score = $userinfo['score'] - $data['price'];
            $userinfo->save();
            $userinfo['avatar']  = 'https://' . $_SERVER['HTTP_HOST']  .$userinfo->avatar;
            $postSuccess=[
                'order_num'=>$order_num,
                'userinfo' =>$userinfo,
            ];
            Db::commit();
            return json(['code'=>1, 'msg'=>'兑换成功', 'data'=>$postSuccess]);
         } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
              $this->error('兑换失败！');
         }
    }



    /**
     * 立即兑换（支付积分）
     */ 
    public function order_pay($order_num,$userId)
    {
        $userId = $this->auth->id;
        $Order = Order::where(['order_num'=>$order_num,'uid'=>$userId])->find();
        if (!$Order) {
            $this->error('订单不存在或已过期');
        }
        if ($Order['order_satae'] != 0) {
            $this->error('订单状态无法兑换');
        }
        $score = User::where('id',$userId)->value('score');
        if ($score < $Order['integral']) {
            $this->error('当前积分不够');
        }
        Order::where(['order_num'=>$order_num,'uid'=>$userId]) ->update(['order_satae' => 1,'pay_time'=>time()]);
        //减少积分，增加记录
        $data = [
            'user_id' => $userId,
            'before'=> $score,
            'score' => $Order['integral'],
            'after' => bcsub($score,$Order['integral']),
            'type' => 2,
            'memo' =>'兑换商品'
        ];
        ScoreLog::create($data);
        User::where('id',$userId)->dec('score', $Order['integral'])->update();
        $this->success('支付成功');
    }


    /**
     * 订单列表
     */ 
    public function order_list() {
        $data = $this->request->post();
        $page = $this->request->post('page/d', 1);
        $limit = $this->request->post('limit/d', 20);
        $userId = $this->auth->id;
        if (!$userId) {
            $this->error('参数错误');
        }
        if($data['order_satae'] == 0){
            $total = Order::where('uid',$userId)->count();
            $result = Order::where('uid',$userId)
            ->field('id,uid,product_id,order_num,product,img,attr,goods_type,integral,goods_number')
            ->page($page, $limit)
            ->order('id','desc')
            ->select();
        }else{
           $total = Order::where('uid',$userId)->where('order_satae',$data['order_satae'])->count();
            $result = Order::where('uid',$userId)
            ->where('order_satae',$data['order_satae'])
            ->field('id,uid,product_id,order_num,product,img,attr,goods_type,integral,goods_number')
            ->page($page, $limit)
            ->order('id','desc')
            ->select(); 
        }
        foreach($result as $k=>$v){
          $result[$k]['img'] = 'https://' . $_SERVER['HTTP_HOST']  .$v['img'];
          $result[$k]['create_time'] = date('Y-m-d',$v['createtime']);
        }
        $last_page = ceil($total / $limit);
        $postData = [
            'total' => $total,
            'data' => $result,
            'last_page'=>$last_page,
        ];
        $this->success('获取成功',$postData);
    }


    /**
     * 订单详情
     */ 
    public function order_details() {
        $order_num = $this->request->post('order_num');
        $userId = $this->auth->id;
        if (!$userId || !$order_num) {
            $this->error('参数错误');
        }
        $info = User::field('username,avatar,score')->where('id',$userId)->find();
        $Order = Order::where(['order_num'=>$order_num,'uid'=>$userId])->find();
        $Order['createtime'] = date('Y-m-d H:i:s',$Order['createtime']);
        $Order['img'] = 'https://' . $_SERVER['HTTP_HOST']  .$Order['img'];
        if ($Order['pay_time']) {
            $Order['pay_time'] = date('Y-m-d H:i:s',$Order['pay_time']);
        }
        $this->success('获取成功',$Order);
    }


}
